package com.km.wskj.itmonitor.pager.wq.forum;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Imgs;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumCard;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.ClearEditText;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/4/6.
 */

//搜索页面
public class ForumSearchListActivity extends LActivity {
    private static final String TAG = "ForumListActivity";

    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.iv_back)
    ImageButton ivBack;
    @BindView(R.id.et_keyword)
    ClearEditText et_keyword;
    @BindView(R.id.tv_search)
    TextView tvSearch;


    private int lastUpdateNum;
    private int pageIndex;
    private MyAdapter mAdapter;
    private List<ForumCard> mForumCards;

    private String mKeyWord;//关键字
    private Activity mActivity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_list);
        //沉浸式
        StatusBarCompat.compat(context, getResources().getColor(R.color.white));
        mActivity = this;
        ButterKnife.bind(this);
    }

    private void initData() {
        onRefresh();
        initPullToRefresh();
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(getResources().getColor(R.color.white90));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);
//        mZrcListView.setHeaderDividersEnabled(false);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });
        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                ForumCard fc = (ForumCard) parent.getItemAtPosition(position);
                Intent t = new Intent(context, ForumDetailActivity.class);
                t.putExtra("data", fc);
                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    private void onRefresh() {
        pdc.forumList(HTTP_TASK_TAG, null, 1, Constant.PageListSize, mKeyWord, new ZxlGenericsCallback<List<ForumCard>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
            }

            @Override
            public void onResponse(List<ForumCard> fcs, int i) {

                if (fcs.size() == 0)
                    normalToasty("暂无数据！");

                mForumCards = fcs;
                lastUpdateNum = fcs.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private void onLoadMore() {
        pdc.forumList(HTTP_TASK_TAG, null, pageIndex + 1, Constant.PageListSize, mKeyWord, new ZxlGenericsCallback<List<ForumCard>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
            }

            @Override
            public void onResponse(List<ForumCard> fcs, int i) {
                lastUpdateNum = fcs.size();
                if (fcs.size() > 0) {
                    mForumCards.addAll(fcs);
                    pageIndex++;
                }
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @OnClick({R.id.iv_back, R.id.tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.tv_search:
                mKeyWord = et_keyword.getText().toString();
                if (mKeyWord.equals("")) {
                    normalToasty("请输入关键字");
                    return;
                }
                hideSoftInput(view.getWindowToken());
                initData();
                //文本观察者
                et_keyword.addTextChangedListener(new MyEditTextChangeListener());

                break;
        }
    }

    private class MyEditTextChangeListener implements TextWatcher {
        /**
         * 编辑框的内容发生改变之前的回调方法
         */
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        /**
         * 编辑框的内容正在发生改变时的回调方法 >>用户正在输入
         * 我们可以在这里实时地 通过搜索匹配用户的输入
         */
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            mZrcListView.setAdapter(null);
        }

        /**
         * 编辑框的内容改变以后,用户没有继续输入时 的回调方法
         */
        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    // 隐藏软键盘
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mForumCards == null) {
                return 0;
            }
            return mForumCards.size();
        }

        @Override
        public Object getItem(int position) {
            return mForumCards.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_card_list);
            ForumCard item = mForumCards.get(position);
            helper.setText(R.id.tv_title, item.title + "");
            String tel = item.tel_no.substring(0, 3) + "****" + item.tel_no.substring(7);
            helper.setText(R.id.tv_author, item.nickname == null ? tel : item.nickname);
            helper.setText(R.id.tv_create_time, item.createTime + "");
            //设置头像
            if (item.head_img != null) {
                Glide.with(mActivity)
                        .load(item.host + item.head_img)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.header_img, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }


            //没有图片的时候才显示内容
            if (item.imgs.size() == 0 && item.imgs == null)
                helper.setText(R.id.tv_content, item.content + "");
            else
                helper.setVisible(R.id.tv_content, false);

            //判断显示图片
            //一张图片
            if (item.imgs.size() > 0 && item.imgs.size() < 3) {
                helper.setVisible(R.id.iv_one_img, true);//显示一张图片控件
                helper.setVisible(R.id.ll_three_img, false);

                Imgs imgs = item.imgs.get(0);

                Glide.with(mActivity)
                        .load(item.host + imgs.file_path + imgs.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_one_img, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
                //显示三张
            } else if (item.imgs.size() >= 3) {
                helper.setVisible(R.id.ll_three_img, true);//显示三张图片控件
                helper.setVisible(R.id.iv_one_img, false);

                Imgs imgs1 = item.imgs.get(0);
                Imgs imgs2 = item.imgs.get(1);
                Imgs imgs3 = item.imgs.get(2);

                Glide.with(mActivity)
                        .load(item.host + imgs1.file_path + imgs1.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                helper.setImageBitmap(R.id.iv_img1, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                Glide.with(mActivity)
                        .load(item.host + imgs2.file_path + imgs2.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img2, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                Glide.with(mActivity)
                        .load(item.host + imgs3.file_path + imgs3.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img3, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }
            return helper.getView();
        }
    }
}
